package com.blog.admin;

import com.blog.controller.BaseController;
import com.blog.model.*;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.ActionKey;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * Created by ${wangjian} on 2017/9/7.
 */

@Before({LoginValidator.class, AdminValidator.class})
public class AdminController extends BaseController {

    public static final AdminService service = new AdminService();

    private static final Admin dao = new Admin().dao();

    /**
     * 登录页
     */
    @Clear(LoginValidator.class)
    public void index() {
        getErrorCookie();
        renderTemplate("login.html");
    }

    @Clear(LoginValidator.class)
    public void login() {
        String userName = getPara("userName");
        Admin admin = dao.getByName(userName);
        getSession().setAttribute("user", admin);
        HttpSession set = getSession();
        set.setMaxInactiveInterval(100000);
        renderTemplate("hello.html");
    }

    public void hello() {
        renderTemplate("hello.html");
    }

    @ActionKey("/blog/admin/logout")
    public void logout() {
        removeSessionAttr("user");
        redirect("/blog/admin");
    }

    /**
     * 后台首页
     */
    public void content() {
        Integer pageNumber = getParaToInt("number", 1);
        Integer logId = getParaToInt("logId");
        Page<Blog> page = service.paginate(pageNumber);
        setAttr("blog", page);
        renderTemplate("list_content.html");
    }

    /**
     * 添加页
     */
    public void addBlog() {
        renderTemplate("addBlog.html");
    }

    public void addContent() {
        UploadFile uploadFile = getFile("file");
        File file = uploadFile.getFile();
        byte[] data = null;
        try {
            InputStream inputStream1 = new FileInputStream(file);
            data = new byte[inputStream1.available()];
            inputStream1.read(data);
            inputStream1.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        String imgBase64ToStr = encoder.encode(data);
        //获取图片后缀
        String type = uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf(".") + 1);
        String str = "";
        if (type.equals("png")) {
            str = "data:image/png;base64,";
        } else if (type.equals("jpg")) {
            str = "data:image/jpeg;base64,";
        }
//        String str1 = type.equals("png") ? str = "data:image/png;base64," : (str = "data:image/jpeg;base64");
        String message = getPara("message");
        String title = getPara("title");
        String content = getPara("edit");
        String digest = getPara("digest");
        String keywords = getPara("keywords");
        String alias = getPara("alias");
        long albumId = service.addImg(message, str, imgBase64ToStr);
        file.delete();
        service.addContent(title, content, digest, keywords, alias, albumId);
        redirect("/blog/admin/content");
    }

    /**
     * 删除页
     */
    public void deleteContent() {
        // todo 不管是同步还是异步，实现删除layer弹窗在确定
        Blog blog = service.queryContent(getParaToInt("logId"));
        Album album = Album.dao.findById(blog.getAlbumId());
        album.delete();
        blog.delete();
        redirect("/blog/admin/content");
    }

    /**
     * 批量删除blog
     */
    public void batchDelete() {
        String[] list = getParaValues("List");
        for (String id : list) {
            Blog blog = new Blog().findById(id);
            Album album = Album.dao.findById(blog.getAlbumId());
            album.delete();
            blog.delete();
        }
        redirect("/blog/admin/content");
    }

    /**
     * 修改页
     */
    public void editBlog() {
        setAttr("blog", service.queryContent(getParaToInt("logId")));
        renderTemplate("editBlog.html");
    }

    public void editContent() {
        Blog blog = new Blog();
        blog.setLogId(getParaToInt("logId"));
        blog.setContent(getPara("content"));
        blog.setClick(getParaToInt("click"));
        blog.setTitle(getPara("title"));
        blog.setDigest(getPara("digest"));
        blog.setKeywords(getPara("keywords"));
        blog.setCreateTime(getParaToDate("createTime"));
        blog.setAlbumId(getParaToLong("albumId"));
        blog.update();
        setAttr("blog", blog);
        redirect("/blog/admin/content");
    }

    /**
     * Album页
     */
    public void album() {
        Integer pageNumber = getParaToInt("number", 1);
        Integer id = getParaToInt("id");
        Page<Album> page = service.page(pageNumber);
        setAttr("album", page);
        renderTemplate("list_album.html");
    }

    /**
     * 删除图片
     */
    public void deleteImg() {
        Album album = service.queryAlbum(getParaToInt("id"));
        album.delete();
        redirect("/blog/admin/album");
    }

    /**
     * 批量删除图片
     */
    public void batchDeleteImg() {
        String[] list = getParaValues("List");
        for (String id : list) {
            Album album = new Album().findById(id);
            album.delete();
        }
        redirect("/blog/admin/album");
    }

    /**
     * 上传图片
     */
    public void uploadImg() {
        UploadFile uploadFile = getFile("file");
        File file = uploadFile.getFile();
        byte[] data = null;
        try {
            InputStream inputStream = new FileInputStream(file);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        String imgBase64ToStr = encoder.encode(data);
        //获取图片后缀
        String type = uploadFile.getFileName().substring(uploadFile.getFileName().lastIndexOf(".") + 1);
        String str = "";
        if (type.equals("png")) {
            str = "data:image/png;base64,";
        } else if (type.equals("jpg")) {
            str = "data:image/jpeg;base64,";
        }
        service.addImg(getPara("message"), str, imgBase64ToStr);
        file.delete();
        redirect("/blog/admin/album");
    }

    /**
     * idea页
     */
    public void idea() {
        Integer pageNumber = getParaToInt("number", 1);
        Integer id = getParaToInt("id");
        Page<Idea> page = service.paginateIdea(pageNumber);
        setAttr("idea", page);
        renderTemplate("list_idea.html");
    }

    /**
     * 添加页
     */
    public void addIdea() {
        String idea = super.getPara("idea");
//        String idea = getRequest().getParameter("idea");
        service.addIdea(idea);
        redirect("/blog/admin/idea");
    }

    /**
     * 删除页
     */
    @ActionKey("/ajax/blog/idea/delete")
    public void deleteIdea() {
        // todo 异步删除成功，但是不会出现成功提示，会出现错误提示
        Ret ret = Ret.ok();
        Idea img = service.queryIdea(getParaToInt("id"));
        img.delete();
        redirect("/blog/admin/idea");  // 异步操作不会直接跳转吗？
        ret.isOk();
    }

    /**
     * 批量删除idea
     */
    public void batchDeleteIdea() {
        // todo 多选删除提示有时间做 2018-3-27
        String[] list = getParaValues("List");
        for (String id : list) {
            Idea idea = new Idea().findById(id);
            idea.delete();
        }
        redirect("/blog/admin/idea");
    }

    /**
     * message页
     */
    public void message() {
        Integer pageNumber = getParaToInt("number", 1);
        Integer id = getParaToInt("id");
        Page<Message> message = service.paginateMessage(pageNumber);
        setAttr("message", message);
        renderTemplate("deleteMessage.html");
    }

    /**
     * 删除留言
     */
    public void deleteMessage() {
        Message message = service.queryMessage(getParaToInt("id"));
        if (null == message) {
            return;
        }
        message.delete();
        redirect("/blog/admin/message");
    }

    /**
     * 批量删除留言
     */
    public void batchDeleteMsg() {
        String[] list = getParaValues("List");
        for (String id : list) {
            Message message = new Message().findById(id);
            message.delete();
        }
        redirect("/blog/admin/message");
    }
}

